import serial.tools.list_ports
import time
import sys
import threading
from datetime import datetime

class USBSerialMonitor:
    def __init__(self, check_interval=1.0):
        self.check_interval = check_interval
        self.current_ports = set()
        self.running = False
        self.monitor_thread = None
        
    def get_serial_ports(self):
        """获取当前所有串口设备"""
        ports = serial.tools.list_ports.comports()
        return {(port.device, port.description, port.vid, port.pid) for port in ports}
    
    def print_port_info(self, port_info, status):
        """打印端口信息"""
        device, description, vid, pid = port_info
        vid_str = f"0x{vid:04X}" if vid else "None"
        pid_str = f"0x{pid:04X}" if pid else "None"
        
        print(f"{status}:{device},{vid_str},{pid_str}", flush=True)
        sys.stdout.flush()
    
    def monitor_ports(self):
        """监控串口设备变化"""
        # print("开始监控USB串口设备...")
        # print("按 Ctrl+C 停止监控")
        # print("=" * 50)
        
        # # 初始化当前端口列表
        self.current_ports = self.get_serial_ports()
        # if self.current_ports:
        #     print("当前已连接的串口设备:")
        #     for port_info in self.current_ports:
        #         self.print_port_info(port_info, "已存在")
        # else:
        #     print("当前没有检测到串口设备")
        
        while self.running:
            try:
                new_ports = self.get_serial_ports()
                
                # 检测新插入的设备
                added_ports = new_ports - self.current_ports
                for port_info in added_ports:
                    self.print_port_info(port_info, "+")
                
                # 检测移除的设备
                removed_ports = self.current_ports - new_ports
                for port_info in removed_ports:
                    self.print_port_info(port_info, "-")
                
                self.current_ports = new_ports
                time.sleep(self.check_interval)
                
            except KeyboardInterrupt:
                break
            except Exception as e:
                print(f"监控过程中发生错误: {e}")
                time.sleep(self.check_interval)
    
    def start(self):
        """启动监控"""
        if not self.running:
            self.running = True
            self.monitor_thread = threading.Thread(target=self.monitor_ports)
            self.monitor_thread.daemon = True
            self.monitor_thread.start()
    
    def stop(self):
        """停止监控"""
        self.running = False
        if self.monitor_thread:
            self.monitor_thread.join()

def main():

    # 创建监控器实例（检查间隔为0.1秒）
    monitor = USBSerialMonitor(check_interval=0.1)
    
    monitor.start()

    # 主线程保持运行
    try:
        while True:
            time.sleep(1)

    except KeyboardInterrupt:
        monitor.stop()
        print("监控已停止", flush=True)

if __name__ == "__main__":
    main()